package com.boot2.core.utils;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author zhangweilin
 * @date 2020/6/23 17:50
 * @Description: 读取环境配置
 */
@CommonsLog
@Component
@Order(Integer.MIN_VALUE)
public class EnvironmentUtil {

    static Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        EnvironmentUtil.environment = environment;
    }

    public static Environment environment() {
        if (null == environment) {
            return SpringUtil.getBean(Environment.class);
        }
        return environment;
    }


    public static String get(String key) {
        return environment().getProperty(key);
    }

    public static String get(String key, String defaultValue) {
        return environment().getProperty(key, defaultValue);
    }


    public static <T> T get(String key, Class<T> targetType) {
        return environment().getProperty(key, targetType);
    }


    public static <T> T get(String key, Class<T> targetType, T defaultValue) {
        return environment().getProperty(key, targetType, defaultValue);
    }

    public static Integer getInt(String key,Integer defaultValue) {
        return environment().getProperty(key,Integer.class, defaultValue);
    }

    public static String getRequiredProperty(String key) {
        return environment().getRequiredProperty(key);
    }

    public static <T> T getRequiredProperty(String key, Class<T> targetType) {
        return environment().getRequiredProperty(key, targetType);
    }
}
